import os
import time
import urllib3
import json
import shutil
import requests
import notify
import deploy_version
import cdn_refresh

def save_version_param(param):
    cwd = os.getcwd()
    with open(os.path.join(cwd, "version.json"), "w") as f:
        f.write(param)

def load_update_version():
    cwd = os.getcwd()
    activity = os.path.join(cwd, "version.json")
    versionName = ""
    with open(activity, "r") as fr:
        content = fr.read()
        versionName = content.strip()
    print(versionName)
    return versionName

def sync_version_to_release(param, url_config, request_configs, context):
    save_version_param(param)
    cwd = os.getcwd()

    test = url_config["TEST"]
    testdir = os.path.join(cwd, "temp/" + test["local_dir"])
    print("temp dir " + testdir)
    if os.path.exists(testdir):
        shutil.rmtree(testdir)
    os.mkdir(testdir)

    config = {"CF_AndroidVersion", "CF_iOSVersion",}
    testconfigs = request_configs(test, testdir, "list", config)
    print("configs: " + str(testconfigs))

    targetVersion = load_update_version()
    print("target version: " + targetVersion)

    version = {}
    for key in testconfigs:
        print("=================================")
        print(key)

        with open(key, "rb") as freader:
            data = json.load(freader)
            if "Android" in key:
                if targetVersion == data["versionName"]:
                    version["Android"] = data["versionName"]
                else:
                    newversion = targetVersion[:len(targetVersion) - 1] + "1"
                    print("Android version " + newversion)
                    if newversion == data["versionName"]:
                        version["Android"] = data["versionName"]
                    else:
                        print("sync version not match version: " + data["versionName"])
            elif "iOS" in key:
                if targetVersion == data["versionName"]:
                    version["iOS"] = data["versionName"]
    print("version: " + str(version))
    if len(version) > 0:
        deploy_version.deploy(version, context)

        time.sleep(10)
        cdnurls = check_version_assets(url_config, testconfigs, context)

        # push cdn
        cdn_refresh.push(cdnurls)
    else:
        context["Status"] = "Fail"
        notify.push_result(context)

def check_version_assets(url_config, testconfigs, context):
    print("check_version_config:")

    cdnurls = []
    awscdn = url_config["AWSCDN"]
    aliyuncdn = url_config["AliyunCDN"]

    result = []
    for key in testconfigs:
        print("=================================")
        print(key)

        versionUrl = url_config["RELEASE"]["version_url"]
        with open(key, "rb") as freader:
            data = json.load(freader)
            patchVersions = data["patchVersions"]
            patchVersions["patchFullAssets"] = data["patchFullAssets"]
            
            for (k, v) in patchVersions.items():
                print("version: " + k + ", download: " + v["downloadUrl"] + ", size " + str(v["size"]))
                assetUrl = versionUrl + "/" + v["downloadUrl"]

                aliyunCdnurl = assetUrl.replace(awscdn, aliyuncdn)
                cdnurls.append(aliyunCdnurl)

                r = requests.get(aliyunCdnurl, stream=True)
                size = r.headers.get("Content-Length")
                print("remote size " + str(size))
                if str(size) != str(v["size"]):
                    result.append(v)
    if len(result) > 0:
        print("sync version fail:\n " + str(result))
        context["Status"] = "Fail"
        exit(0)
    else:
        print("sync version success")
        context["Status"] = "Success"
    notify.push_result(context)
    return cdnurls